import axios from "axios";
import qs from 'qs';
import store from '@/store'
import router from '../router'
import Vue from 'vue'
// 全局配置
axios.defaults.baseURL = 'http://192.168.1.9:3000/api';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.timeout = 10000;

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    if (store.getters["login/getIsLogin"]) {
        config.headers.common['Authorization'] = "Bearer " + store.getters["login/getUserInfo"].token;
    }
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // console.log(response)
    if (response.data.code == 403) {
        store._mutations["login/removeUserInfo"][0]()
        Vue.prototype.$message({
            message: "登陆过期，请重新登录",
            type: "error",
            duration: 3000,
            onClose() {
                router.replace({ path: '/admin/login' })
            }
        });

    }
    // 对响应数据做点什么
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

// 封装请求方式
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params
        }).then(data => {
            resolve(data.data)
        }).catch(err => {
            reject(err)
        })
    })
}
// 封装post请求
export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, qs.stringify(params))
            .then(data => {
                resolve(data.data)
            }).catch(err => {
                reject(err)
            })
    })
}
// 封装put请求
export function put(url, params) {
    return new Promise((resolve, reject) => {
        axios.put(url, params)
            .then(data => {
                resolve(data.data)
            }).catch(err => {
                reject(err)
            })
    })
}
// 封装delete请求
export function deletes(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, { data: params })
            .then(data => {
                resolve(data.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}
